/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package it.unibo.as.SessionBeans;

import it.unibo.as.db.User;
import it.unibo.as.util.BCrypt;
import javax.ejb.Stateless;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceUnit;

/**
 *
 * @author Johnny
 */

/*lsdldsldfsl*/
@Stateless
public class AuthenticationBean implements AuthenticationBeanLocal {

    @PersistenceUnit
    EntityManagerFactory emf;

    @Override
    public Boolean LogInWithPwd(String nickname, String password) {
        User user;
        Boolean valid;
        user = (User)emf.createEntityManager().createNamedQuery("User.findByNickname")
                                 .setParameter("nickname", nickname)
                                 .getSingleResult();
        valid = BCrypt.checkpw(password, user.getPassword());

        return valid;
    }

    @Override
    public Boolean SignUp(String fname, String lname, String nickname, String email, String password) {
        User user = new User();
        Boolean exist = false;
        try{
        user = (User)emf.createEntityManager().createNamedQuery("User.findByNickname")
                                 .setParameter("nickname", nickname)
                                 .getSingleResult();
        }
        catch(NoResultException ex){
            exist = false;
        }

        if(!exist){
            user.setEmail(email);
            user.setFname(fname);
            user.setLastlog(null);
            user.setLname(lname);
            user.setNickname(nickname);
            user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
            user.setPoints(0);

            emf.createEntityManager().persist(user);

            return true;
        }


        return false;
    }


    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

 
}
